<?php


namespace app\api\controller;
use app\validate\OrderCheck;
use library\Controller;
use think\Db;
use think\Exception;
use think\Request;
use app\common\model\YinuoOrder;
class Order extends Base
{
    //预约下单
    public function create_order(Request $request,OrderCheck $check,YinuoOrder $order){
        try {
            $param = $request->param();
            $result = $check->scene('create_order')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                $msg = $order->create_order($param);
                if ($msg==1) {
                    $YinuoOrder = new YinuoOrder();
                    $create_order = $YinuoOrder::where(["member_id"=>$param['member_id']])->order("id desc")->find();
                    $this->self_kaiqi($create_order);
                    return $this->api_result(200, '请求成功', $create_order);
                } else {
                    return $this->api_result(400, $msg, []);
                }
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '请求失败', []);
        }
    }

    //自开启
    public function self_kaiqi($create_order){
        if($create_order['shuxing']=='self'){
            Db::table("store_yinuo_order")->where(['id'=>$create_order['id']])->update(['end_count'=>1]);
            $device_sn = Db::table("store_device")->where(['id'=>$create_order['device_id']])->value('sn');
            $order_no = $create_order['order_no'];
            $start_at = date('Y-m-d H:i:s',time()-300);
            $end_at = date('Y-m-d H:i:s');
            $row = Db::table("dev")->field("id")->where(['device_sn' => $device_sn])->where("create_at>='$start_at'")->where("create_at<='$end_at'")->find();
            if($row){
                $find = Db::table("dev")->where(['device_sn' => $device_sn])->where("bin_code='02'")->order("id desc")->limit(1)->find();
                if($find){

                    $connect = $find['connect'];

                    $baowen = "680D00000099" . $device_sn . $order_no . '000000000100358f'.$connect.'200358f6666777788889999';
                    $baowen_res = str_split($baowen, 2);

                    $answer = '';
                    foreach ($baowen_res as $k => &$v) {
                        $answer .= chr(intval('0x' . $v, 16));
                    }
                    $buffer = $answer;
                    $client = stream_socket_client('tcp://localhost:9003');
                    fwrite($client, $buffer);

                    sleep(2);
                    $this->kaiqi($device_sn,$order_no);
                }
            }
        }
    }


    //我的订单
    public function my_order(Request $request,OrderCheck $check,YinuoOrder $order){
        try {
            $param = $request->param();
            $result = $check->scene('my_order')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                $data = $order->my_order($param);
                return $this->api_result(200, '请求成功', $data);
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '请求失败', []);
        }
    }

    //我的订单
    public function master_order(Request $request,OrderCheck $check,YinuoOrder $order){
        try {
            $param = $request->param();
            $result = $check->scene('master_order')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                $data = $order->master_order($param);
                return $this->api_result(200, '请求成功', $data);
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '请求失败', []);
        }
    }



    //余额支付
    public function amount_pay(Request $request,OrderCheck $check,YinuoOrder $order){
        Db::startTrans();
        try {
            $param = $request->param();
            $result = $check->scene('amount_pay')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                $data = $order->amount_pay($param);
                if ($data==1) {
                    Db::commit();
                    return $this->api_result(200, '请求成功', $data);
                }else{
                    return $this->api_result(400, $data, []);
                }
            }
        } catch (\Exception $e) {
            Db::rollback();
            return $this->api_result(400, '请求失败', []);
        }
    }


    //订单评价
    public function evaluate(Request $request,OrderCheck $check,YinuoOrder $order){
        Db::startTrans();
        try {
            $param = $request->param();
            $result = $check->scene('evaluate')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                $data = $order->evaluate($param);
                if ($data==1) {
                    Db::commit();
                    return $this->api_result(200, '请求成功', $data);
                }else{
                    return $this->api_result(400, $data, []);
                }
            }
        } catch (\Exception $e) {
            Db::rollback();
            return $this->api_result(400, '请求失败', []);
        }
    }

    //完成订单
    public function complete_order(Request $request){
        $param = $request->param();
        $device_id = $param['device_id'];
        $order = Db::table("store_yinuo_order")->where(['device_id'=>$device_id])->order("id desc")->find();
        if(($order)&&($order['shuxing']=='self')&&($order['member_id']==$param['member_id'])){
            $order['park'] = Db::table("store_park")->where(['id'=>$order['park_id']])->find();
            $time = time();
            $order['use_time'] = (int)(($time-strtotime($order['start_time']))/60);
            //$order['park_price_wait'] = sprintf('%.2f',(($order['use_time']/60)*$order['park']['price']));
            //$order['park_price'] = $order['park_price_wait'];
            $order['park_price_wait'] = 0;
            $order['park_price'] = 0;
            $total_price = sprintf('%.2f',$order['park_price']+$order['charge_price']);
            Db::table("store_yinuo_order")->where(['id'=>$order['id']])->update(['status'=>5,'end_time'=>date('Y-m-d H:i:s'),'charge_end_time'=>date('Y-m-d H:i:s'),'park_price'=>$order['park_price'],'total_price'=>$total_price,'paid_price'=>$total_price]);
            Db::table("store_device")->where(['id' => $order['device_id']])->update(['status' => 1]);
            Db::table("store_park")->where(['id' => $order['park_id']])->update(['status' => 1]);
            $this->close_device($order);
            return $this->api_result(200, '请求成功', 1);
        }else{
            return $this->api_result(400, '此电桩已被其他人占用', 1);
        }
    }


    //自充电关闭
    public function close_device($order){
        $device_sn = Db::table("store_device")->where(['id'=>$order['device_id']])->value('sn')??'';
        if(!empty($device_sn)) {
            $member_id = $order['member_id']??0;
            $phone = Db::table("store_member")->where(['id' => $member_id])->value('phone')??'';
            if (!empty($phone)) {
                $this->sms_end($phone, $order['id']);
            }

            $start_at = date('Y-m-d H:i:s', time() - 300);
            $end_at = date('Y-m-d H:i:s');
            $row = Db::table("dev")->field("id")->where(['device_sn' => $device_sn])->where("create_at>='$start_at'")->where("create_at<='$end_at'")->find();
            if ($row) {

                $find = Db::table("dev")->where(['device_sn' => $device_sn])->order("id desc")->limit(1)->find();
                if ($find) {

                    $connect = $find['connect'];

                    $baowen = "680D00000098" . $device_sn . "0100358f" . $connect . '200358f6666777788889999';
                    $baowen_res = str_split($baowen, 2);

                    $answer = '';
                    foreach ($baowen_res as $k => &$v) {
                        $answer .= chr(intval('0x' . $v, 16));
                    }
                    $buffer = $answer;
                    $client = stream_socket_client('tcp://localhost:9003');
                    fwrite($client, $buffer);
                }

            }
            $this->guanbi($device_sn);
        }
    }


    //去充电订单
    public function charging_order(Request $request){
        $param = $request->param();

        $order = Db::table("store_yinuo_order")->where(['id'=>$param['id']])->find();
        if(empty($order['start_time'])){
            Db::table("store_yinuo_order")->where(['id'=>$param['id']])->update(['status'=>3,'start_time'=>date('Y-m-d H:i:s'),'charge_start_time'=>date('Y-m-d H:i:s')]);
        }else{
            Db::table("store_yinuo_order")->where(['id'=>$param['id']])->update(['status'=>3,'charge_start_time'=>date('Y-m-d H:i:s')]);
        }


        $order_no = $order['order_no'];
        $order_no = $order_no . '0';

        $device_sn = Db::table("store_device")->where(['id'=>$order['device_id']])->value('sn');

        $start_at = date('Y-m-d H:i:s',time()-300);
        $end_at = date('Y-m-d H:i:s');
        $row = Db::table("dev")->field("id")->where(['device_sn' => $device_sn])->where("create_at>='$start_at'")->where("create_at<='$end_at'")->find();
        if($row){
            $find = Db::table("dev")->where(['device_sn' => $device_sn])->where("bin_code='02'")->order("id desc")->limit(1)->find();
            if($find){

                $connect = $find['connect'];

                $baowen = "680D00000099" . $device_sn . $order_no . '000000000100358f'.$connect.'200358f6666777788889999';
                $baowen_res = str_split($baowen, 2);

                $answer = '';
                foreach ($baowen_res as $k => &$v) {
                    $answer .= chr(intval('0x' . $v, 16));
                }
                $buffer = $answer;
                $client = stream_socket_client('tcp://localhost:9003');
                fwrite($client, $buffer);

                sleep(2);
                $this->kaiqi($device_sn,$order_no);
            }
        }

        return $this->api_result(200, '请求成功', 1);
    }

    public function kaiqi($device_sn,$order_no,$type=1){
        if($type==2){
            $find = Db::table("dev")->where(['device_sn' => $device_sn])->where("bin_code='04'||bin_code='13'")->order("id desc")->limit(1)->find();
        }else{
            $find = Db::table("dev")->where(['device_sn' => $device_sn])->order("id desc")->limit(1)->find();
        }

        if($find){

            $connect = $find['connect'];

            $baowen = "680D00000099" . $device_sn . $order_no . '000000000100358f'.$connect.'200358f6666777788889999';
            $baowen_res = str_split($baowen, 2);

            $answer = '';
            foreach ($baowen_res as $k => &$v) {
                $answer .= chr(intval('0x' . $v, 16));
            }
            $buffer = $answer;
            $client = stream_socket_client('tcp://localhost:9003');
            fwrite($client, $buffer);
        }

    }


    public function info(Request $request){
        $param = $request->param();
        $find = Db::table("store_yinuo_order")->where(['type'=>1,'status'=>3])->where(['id'=>$param['id']])->find();
        if($find) {
            $device_sn = Db::table("store_device")->where(['id' => $find['device_id']])->value('sn');
            if($find['dev_qiang_status']!='是'){
                $this->kaiqi($device_sn, $find['order_no'],2);
            }
        }else{
            $find = Db::table("store_yinuo_order")->where(['id'=>$param['id']])->find();
        }
        return $this->api_result(200, '请求成功', $find);
    }

    public function sms_end($mobile=18646369723,$id=1){
        $ishave = Db::table("store_mobile_code2")->where(['mobile'=>$mobile,'type'=>'end','order_id'=>$id])->find();
        if(empty($ishave)){
            $url = "https://api.guoyangyun.com/api/sms/smsoto.htm?appkey=1121362612202412070944571519586&appsecret=e238c0a5f684da68af56af66c2cfe66f&mobile=$mobile&smsSignId=3ff0685b3d464bd09404862b630e2dd2&templateId=036629bcfad7402e9b6ab71cc3391cb7";
            $res = file_get_contents($url);
            $arr = json_decode($res,true);
            if($arr){
                if($arr['msg']=='成功'){
                    Db::table("store_mobile_code2")->insert(['mobile'=>$mobile,'type'=>'end','order_id'=>$id,'add_time'=>date('Y-m-d H:i:s')]);
                }
            }
        }
    }

    public function sms_guzhuang($mobile=18646369723,$id=1){
        $ishave = Db::table("store_mobile_code2")->where(['mobile'=>$mobile,'type'=>'guzhuang','order_id'=>$id])->find();
        if(empty($ishave)){
            $url = "https://api.guoyangyun.com/api/sms/smsoto.htm?appkey=1121362612202412070944571519586&appsecret=e238c0a5f684da68af56af66c2cfe66f&mobile=$mobile&smsSignId=3ff0685b3d464bd09404862b630e2dd2&templateId=19a76c75ff07475b8601258830396186";
            $res = file_get_contents($url);
            $arr = json_decode($res,true);
            if($arr){
                if($arr['msg']=='成功'){
                    Db::table("store_mobile_code2")->insert(['mobile'=>$mobile,'type'=>'guzhuang','order_id'=>$id,'add_time'=>date('Y-m-d H:i:s')]);
                }
            }
        }
    }


    public function info2(Request $request){
        $param = $request->param();
        $find = Db::table("store_yinuo_order")->where(['type'=>1,'status'=>3])->where(['id'=>$param['id']])->find();
        if($find){
            if($find['start_count']<=60){
                if($find['dev_qiang_status']!='是'){
                    $device_sn = Db::table("store_device")->where(['id'=>$find['device_id']])->value('sn');
                    $start_count = $find['start_count']+1;
                    Db::table("store_yinuo_order")->where(['id'=>$param['id']])->update(['start_count'=>$start_count]);

                    $start_at = date('Y-m-d H:i:s',time()-300);
                    $end_at = date('Y-m-d H:i:s');
                    $row = Db::table("dev")->field("id")->where(['device_sn' => $device_sn])->where("create_at>='$start_at'")->where("create_at<='$end_at'")->find();
                    if($row) {
                        $this->kaiqi($device_sn, $find['order_no'],2);
                    }
                }
            }else{
                Db::table("store_yinuo_order")->where(['id'=>$param['id']])->update(['status'=>4,'remark'=>'故障结束','end_time'=>date('Y-m-d H:i:s'),'charge_end_time'=>date('Y-m-d H:i:s')]);
                $order = Db::table("store_yinuo_order")->where(['id'=>$param['id']])->find();
                if($order) {
                    $device_sn = Db::table("store_device")->where(['id' => $order['device_id']])->value('sn');
                    if ($device_sn) {
                        Db::table("store_device")->where(['id' => $order['device_id']])->update(['status'=>2]);

                        $member_id = $order['member_id'];
                        $phone = Db::table("store_member")->where(['id'=>$member_id])->value('phone');
                        if($phone){
                            $this->sms_guzhuang($phone,$order['id']);
                        }


                        $this->guanbi($device_sn);
                    }
                }
            }
        }else{
            $find = Db::table("store_yinuo_order")->where(['id'=>$param['id']])->find();
        }

        return $this->api_result(200, '请求成功', $find);
    }


    public function info3(Request $request){
        $param = $request->param();
        $arr = [
            '0:00~0:30','0:30~1:00','1:00~1:30','1:30~2:00','2:00~2:30','2:30~3:00','3:00~3:30','3:30~4:00','4:00~4:30','4:30~5:00',
            '5:00~5:30','5:30~6:00','6:00~6:30','6:30~7:00','7:00~7:30','7:30~8:00','8:00~8:30','8:30~9:00',
            '9:00~9:30','9:30~10:00','10:00~10:30','10:30~11:00','11:00~11:30','11:30~12:00','12:00~12:30','12:30~13:00',
            '13:00~13:30','13:30~14:00','14:00~14:30','14:30~15:00','15:00~15:30','15:30~16:00','16:00~16:30','16:30~17:00',
            '17:00~17:30','17:30~18:00','18:00~18:30','18:30~19:00','19:00~19:30','19:30~20:00','20:00~20:30','20:30~21:00',
            '21:00~21:30','21:30~22:00','22:00~22:30','22:30~23:00','23:00~23:30','23:30~24:00'
        ];
        $v = Db::table("store_yinuo_order")->where(['id'=>$param['id']])->find();
        if($v){
            if($v['status']==1){
                $v['status_name'] = '订单状态：预约充电/停车';
            }
            if($v['status']==2){
                $v['status_name'] = '订单状态：放行后 已预约';
            }
            if($v['status']==3){
                $v['status_name'] = '订单状态：充电/停车中';
            }
            if($v['status']==4){
                $v['status_name'] = '订单状态：充电/停车完成（待支付）';
            }
            if($v['status']==5){
                $v['status_name'] = '订单状态：已支付（待评论）';
            }
            if($v['status']==6){
                $v['status_name'] = '订单状态：已评论（全部完成）';
            }

            if($v['type']==1){
                $v['type_name'] = '预约充电';
            }
            if($v['type']==2){
                $v['type_name'] = '预约停车';
            }

            $v['member'] = Db::table("store_member")->where(['id'=>$v['member_id']])->find();
            $v['device'] = Db::table("store_device")->where(['id'=>$v['device_id']])->find();
            $v['park'] = Db::table("store_park")->where(['id'=>$v['park_id']])->find();
            $v['station'] = Db::table("store_power_station")->where(['id'=>$v['station_id']])->find();
            $v['user'] = Db::table("store_member")->where(['id'=>$v['user_id']])->find();
            $v['car'] = Db::table("store_car")->where(['id'=>$v['car_id']])->find();
            $v['car_tel'] = $v['member']['phone'];

            $v['time'] = strtotime($v['create_at']);
            $v['jiezhi'] = $v['time']+1800;

            $time = time();
            $v['daojishi'] = $v['jiezhi'] - $time;
            if($v['daojishi']<0){
                $v['daojishi'] = 0;
            }

            $v['use_time'] = (int)(($time-strtotime($v['start_time']))/60);
            $v['use_time2'] = (int)((strtotime($v['paid_time'])-strtotime($v['start_time']))/60);
            $hour = ceil($v['use_time']/60);

            if($v['type']==2){
                $v['park_price_wait'] = sprintf('%.2f',($hour*$v['park']['price']));
            }else{
                $v['park_price_wait'] = sprintf('%.2f',($hour*$v['park']['price']));

                $device = Db::table("store_device")->where(['id'=>$v['device_id']])->find();
                $free_park_hour = $device['free_park_hour']??0;
                $free_park_time = $free_park_hour*3600;
                $park_time = time()-strtotime($v['start_time']);
                if($free_park_time>$park_time){
                    $v['park_price_wait'] = 0;
                    if($v['charging_capacity']<20){
                        $xiaoshi = ceil($park_time/3600);
                        $v['park_price_wait'] = sprintf('%.2f',$xiaoshi*1);
                    }
                }else{
                    $cha = $park_time-$free_park_time;
                    $xiaoshi = ceil($cha/3600);
                    $v['park_price_wait'] = sprintf('%.2f',$xiaoshi*$v['park']['price']);
                }
            }


            if($v['status']==4){
                if($v['charging_capacity']>0){
                    $v['du'] = sprintf('%.2f',$v['charging_amount']/$v['charging_capacity']);
                }else{
                    $v['du'] = 0;
                }
            }elseif ($v['status']==5){
                if($v['charging_capacity']>0){
                    $v['du'] = sprintf('%.2f',$v['charge_price']/$v['charging_capacity']);
                }else{
                    $v['du'] = 0;
                }
            }elseif ($v['status']==6){
                if($v['charging_capacity']>0){
                    $v['du'] = sprintf('%.2f',$v['charge_price']/$v['charging_capacity']);
                }else{
                    $v['du'] = 0;
                }
            }else{
                $v['du'] = 0;
            }


            if($v['device']){
                $v['cost_price1'] = '尖电价：'.sprintf('%.4f',$v['device']['price']).'元/度 <br>服务费：'.sprintf('%.4f',$v['device']['service_price']).'元/度 <br>';
                $cost_time1 = '';
                $v['cost_price2'] = '峰电价：'.sprintf('%.4f',$v['device']['price2']).'元/度 <br>服务费：'.sprintf('%.4f',$v['device']['service_price2']).'元/度 <br>';
                $cost_time2 = '';
                $v['cost_price3'] = '平电价：'.sprintf('%.4f',$v['device']['price3']).'元/度 <br>服务费：'.sprintf('%.4f',$v['device']['service_price3']).'元/度 <br>';
                $cost_time3 = '';
                $v['cost_price4'] = '谷电价：'.sprintf('%.4f',$v['device']['price4']).'元/度 <br>服务费：'.sprintf('%.4f',$v['device']['service_price4']).'元/度 <br>';
                $cost_time4 = '';
                $cost_model = json_decode($v['device']['cost_model'],true);
                if($cost_model) {
                    foreach ($cost_model as $kk => &$vv) {
                        if ($vv == 1) {
                            $cost_time1 .= $arr[$kk] . ' ';
                        }
                        if ($vv == 2) {
                            $cost_time2 .= $arr[$kk] . ' ';
                        }
                        if ($vv == 3) {
                            $cost_time3 .= $arr[$kk] . ' ';
                        }
                        if ($vv == 4) {
                            $cost_time4 .= $arr[$kk] . ' ';
                        }
                    }

                    $v['cost_price1'] .= ' 时段：' . $cost_time1;
                    $v['cost_price2'] .= ' 时段：' . $cost_time2;
                    $v['cost_price3'] .= ' 时段：' . $cost_time3;
                    $v['cost_price4'] .= ' 时段：' . $cost_time4;
                }else{
                    $v['cost_price1'] = ' ';
                    $v['cost_price2'] = ' ';
                    $v['cost_price3'] = ' ';
                    $v['cost_price4'] = ' ';
                }
            }else{
                $v['cost_price1'] = ' ';
                $v['cost_price2'] = ' ';
                $v['cost_price3'] = ' ';
                $v['cost_price4'] = ' ';
            }
        }
        return $this->api_result(200, '请求成功', $v);
    }


    //去支付订单
    public function topay_order(Request $request){
        $param = $request->param();
        Db::table("store_yinuo_order")->where(['id'=>$param['id']])->update(['status'=>4,'end_time'=>date('Y-m-d H:i:s')]);

        $order = Db::table("store_yinuo_order")->where(['id'=>$param['id']])->find();
        if($order){
            $device_sn = Db::table("store_device")->where(['id'=>$order['device_id']])->value('sn');
            if($device_sn){
                Db::table("store_yinuo_order")->where(['id'=>$param['id']])->update(['charge_end_time'=>date('Y-m-d H:i:s')]);

                $member_id = $order['member_id'];
                $phone = Db::table("store_member")->where(['id'=>$member_id])->value('phone');
                if($phone){
                    $this->sms_end($phone,$order['id']);
                }


                $start_at = date('Y-m-d H:i:s',time()-300);
                $end_at = date('Y-m-d H:i:s');
                $row = Db::table("dev")->field("id")->where(['device_sn' => $device_sn])->where("create_at>='$start_at'")->where("create_at<='$end_at'")->find();
                if($row) {

                    $find = Db::table("dev")->where(['device_sn' => $device_sn])->order("id desc")->limit(1)->find();
                    if($find){

                        $connect = $find['connect'];

                        $baowen = "680D00000098" . $device_sn . "0100358f".$connect.'200358f6666777788889999';
                        $baowen_res = str_split($baowen, 2);

                        $answer = '';
                        foreach ($baowen_res as $k => &$v) {
                            $answer .= chr(intval('0x' . $v, 16));
                        }
                        $buffer = $answer;
                        $client = stream_socket_client('tcp://localhost:9003');
                        fwrite($client, $buffer);
                    }

                }

                $this->guanbi($device_sn);
            }
        }

        return $this->api_result(200, '请求成功', 1);
    }


    public function guanbi($device_sn){
        sleep(2);

        $find = Db::table("dev")->where(['device_sn' => $device_sn])->order("id desc")->limit(1)->find();
        if($find){

            $connect = $find['connect'];

            $baowen = "680D00000098" . $device_sn . "0100358f".$connect.'200358f6666777788889999';
            $baowen_res = str_split($baowen, 2);

            $answer = '';
            foreach ($baowen_res as $k => &$v) {
                $answer .= chr(intval('0x' . $v, 16));
            }
            $buffer = $answer;
            $client = stream_socket_client('tcp://localhost:9003');
            fwrite($client, $buffer);
        }

    }


    //处理订单进场
    public function handle_order(Request $request){
        $param = $request->param();
        Db::table("store_yinuo_order")->where(['id'=>$param['id']])->update(['status'=>2,'start_time'=>date('Y-m-d H:i:s')]);
        return $this->api_result(200, '请求成功', 1);
    }


    //放行订单
    public function fangxing_order(Request $request){
        $param = $request->param();
        Db::table("store_yinuo_order")->where(['id'=>$param['id']])->update(['is_out'=>1,'out_time'=>date('Y-m-d H:i:s')]);
        return $this->api_result(200, '请求成功', 1);
    }


    //查看评价
    public function evaluate_info(Request $request){
        $param = $request->param();
        $data = Db::table("store_station_comment")->where(['order_id'=>$param['order_id']])->find();
        $data['user'] = Db::table("store_member")->where(['id'=>$data['user_id']])->find();
        $data['order'] = Db::table("store_yinuo_order")->where(['id'=>$data['user_id']])->find();
        $data['station'] = Db::table("store_power_station")->where(['id'=>$data['station_id']])->find();
        return $this->api_result(200, '请求成功', $data);
    }

}